<?php

namespace app\model;

use core\BaseModel;

class Tweet extends BaseModel
{
    protected string $table = 'tweets';

    /**
     * 关联关系：获取发布此推文的用户
     */
    public function user(): ?User
    {
        // 这是一个简单的关系实现
        foreach ($_SESSION['users'] ?? [] as $username => $userData) {
            if ($userData['id'] === $this->user_id) {
                $userData['username'] = $username;
                return (new User($userData))->syncOriginal();
            }
        }
        return null;
    }

    /**
     * 获取此推文的所有回复
     */
    public function replies(): array
    {
        $replies = array_filter($_SESSION['tweets'], function ($tweet) {
            return ($tweet['parent_id'] ?? null) === $this->id;
        });

        uasort($replies, fn($a, $b) => $a['timestamp'] - $b['timestamp']);

        return array_map(fn($item) => (new static($item))->syncOriginal(), $replies);
    }
}
